/**
 * @author weileiming
 * @description 封装一个请求
 */

import Taro from '@tarojs/taro';


// 基础 URL
const BASE_URL = process.env.TARO_APP_API_URL;

// 初始化请求头
let headers = {
  'Content-Type': 'application/json'
};

// 清除请求头
function clearHeaders() {
  headers = {};
}

// 处理响应
function handleResponse(response) {
  const { statusCode, data } = response;

  if (statusCode >= 200 && statusCode < 300) {
    if (data.code === 0) {
      return data.data;
    }
  }
  else {
    throw new Error(`HTTP Error: ${statusCode}`);
  }
}

// 发起请求
async function request(options) {
  try {
    const { url, headers: customHeaders = {}, ...rest } = options;
    const fullUrl = `${BASE_URL}${url}`;
    // 在每次请求时获取最新的 token
    const token = Taro.getStorageSync('token') || '';
    const authHeaders = {
      ...headers,
      ...customHeaders,
      'Token': `Bearer eyJhbGciOiJIUzI1NiJ9.eyJ0ZW5hbnRJZCI6MSwidXNlcklkIjoxMDE5LCJ1c2VybmFtZSI6ImNlc2hpIiwic2hvd1ByaXZhY3kiOjAsImlzcyI6Im1hcmtldGluZy1ib3BzIn0.34ni0R3S4pAZ1kNmwOtzOY4_GeTxf5zsihV8Yu5haho`,
    };
    console.log('🚀 clearlove  - Log ~ request ~ authHeaders: ', authHeaders);
    const response = await Taro.request({
      url: fullUrl,
      header: authHeaders,
      ...rest,
    });
    return handleResponse(response);
  } catch (error) {
    throw error;
  }
}

// 封装 GET 请求
async function get(url, data) {
  return request({
    url,
    method: 'GET',
    data,
  });
}

// 封装 POST 请求
async function post(url, data) {
  return request({
    url,
    method: 'POST',
    data,
  });
}

// 封装 PUT 请求
async function put(url, data) {
  return request({
    url,
    method: 'PUT',
    data,
  });
}

// 封装 DELETE 请求
async function del(url, data) {
  return request({
    url,
    method: 'DELETE',
    data,
  });
}

export {
  clearHeaders,
  get,
  post,
  put,
  del
};
    